package com.example.infrastructure.config;


import com.example.infrastructure.service.EnvironmentService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.Resource;


/**
 * 跨域配置，解决跨域问题
 */
@Configuration
public class CorsConfig {

    @Resource
    private EnvironmentService envService;

    @Bean("CorsFilter")
    public CorsFilter corsFilter() {

        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        /*是否允许请求带有验证信息*/
        // 跨域配置下使用session，需要前端配合使用设置 axios.defaults.withCredentials = true
        corsConfiguration.setAllowCredentials(true);
        /*允许访问的客户端域名*/
        if (envService.isDevelopmentEnvironment()){
            // dev环境下，允许指定或任何域名跨域访问
            corsConfiguration.addAllowedOriginPattern("*");
        }else {
            // prod环境下，只允许客户端应用所在的顶级域名访问
            // 正式环境
            // corsConfiguration.addAllowedOriginPattern("*");
        }
        /*允许服务端访问的客户端请求头*/
        corsConfiguration.addAllowedHeader("*");
        /*允许访问的方法名,GET POST等*/
        corsConfiguration.addAllowedMethod("*");

        corsConfiguration.addAllowedMethod(HttpMethod.GET);
        corsConfiguration.addAllowedMethod(HttpMethod.POST);
        corsConfiguration.addAllowedMethod(HttpMethod.DELETE);
        corsConfiguration.addAllowedMethod(HttpMethod.PUT);
        corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS);

        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);

    }

}
